package utils.binarytree;

import java.util.LinkedList;
import java.util.Random;

/**
 * @author yaohuaiying
 * @create 2018-02-08 14:23
 **/
public class BinaryTree {
    private TreeNode root;

    public BinaryTree(int data) {
        this.root = new TreeNode(data);
    }

    public BinaryTree() {
        this.root = null;
    }

    public int getMaxDeepth(){
        return TreeNode.getMaxDeepthHelper(root);
    }

    public void treePrint(int tempSize){
        treePrintHelper(root,0,tempSize);
    }

    private void treePrintHelper(TreeNode currentTreeNode, int i, int temp){
        if(currentTreeNode == null){
            return;
        }
        treePrintHelper(currentTreeNode.getRight(), i+temp,temp);
        for(int k=0; k<i; k++){
            System.out.print(" ");
        }
        System.out.println("" + currentTreeNode.getData());
        treePrintHelper(currentTreeNode.getLeft(), i+temp,temp);
    }

    public void BFSPrint(){
        LinkedList<TreeNode> BFSQueue = new LinkedList<>();
        if(root != null) {
            TreeNode currentNode = root;
            BFSQueue.addLast(root);
            while (!BFSQueue.isEmpty()) {
                //父出 子进
                currentNode =BFSQueue.removeFirst();
                System.out.print(currentNode.getData() + "  ");
                if(currentNode.getLeft() != null){
                    BFSQueue.addLast(currentNode.getLeft());
                }
                if(currentNode.getRight() != null){
                    BFSQueue.addLast(currentNode.getRight());
                }
            }
        }
        System.out.println();
    }


    public void insert(int value){
        if(root == null){
            root = new TreeNode(value);
        }else{
            insertHelp(value,this.root);
        }
    }

    private void insertHelp(int value, TreeNode currTreeNode){
        if(value < currTreeNode.getData()){
            if(currTreeNode.getLeft() == null){
                currTreeNode.setLeft(new TreeNode(value));
            }else {
                //左
                insertHelp(value, currTreeNode.getLeft());
            }
        }
        if(value > currTreeNode.getData()){
            if(currTreeNode.getRight() == null){
                currTreeNode.setRight(new TreeNode(value));
            }else {
                insertHelp(value, currTreeNode.getRight());
            }
        }
        if(value == currTreeNode.getData()){
            ;
        }
    }

    public static BinaryTree createBinaryTree(int size){
        BinaryTree binaryTree = new BinaryTree();
        Random random = new Random();
        for(int i=0; i<size; i++){
            binaryTree.insert(random.nextInt(50));
        }
        return binaryTree;
    }

    public TreeNode getRoot() {
        return root;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }
}
